import React, { useState } from 'react';
import logType from '../common/const/logType';
import { formatLog, Log } from './common';


export interface SummitOptions {
    id: number;
    includeTags: string[];
    excludeTags: string[];
    startDate: number;
    endDate: number;
    index: number;
    level: logType[];
}

let keepAliveTimeoutId: NodeJS.Timeout;
let currentIndex;
let websocket: WebSocket;
const maxShow = 200;

export function useRealtimeLogs(value: Log[]) {
    const [logs, setLogs] = useState(value);

    function listenLogs(opts: SummitOptions) {
        const { includeTags, excludeTags, level, id } = opts;
        const host = location.host;
        const wsPro = location.protocol === 'http:' ? 'ws:' : 'wss:';

        websocket = new WebSocket(`${wsPro}//${host}/ws/realtimeLog`);

        currentIndex = 0;
        websocket.onmessage = function(evt: any) {
            let data = JSON.parse(evt.data).message;
            let formatLogArray = formatLog(data);
            let temp = logs;
            temp.unshift(formatLogArray);
            if (temp.length > maxShow) {
                temp.length = maxShow;
            }
            setLogs(Object.assign([], temp));
        };

        websocket.onclose = function() {
            clearTimeout(keepAliveTimeoutId);
        };

        websocket.onopen = function() {
            websocket.send(
                JSON.stringify({
                    type: 'INIT',
                    include: includeTags,
                    exclude: excludeTags,
                    level,
                    id
                })
            );

            keepAliveTimeoutId = setInterval(function() {
                websocket.send(
                    JSON.stringify({
                        type: 'KEEPALIVE'
                    })
                );
            }, 5000);
        };
        console.log(`websocket! start`);
    }

    function stopLogs() {
        websocket.close();
        console.log(`websocket! close`);
    }

    return [logs, listenLogs, stopLogs];
}

export function useInput(initialValue = '') {
    const [value, setValue] = useState(initialValue);

    return {
        value,
        setValue,
        reset: () => setValue(''),
        bind: {
            value,
            onChange: event => {
                setValue(event.target.value);
            }
        }
    };
}
